//
//  TransferViewController.m
//  Bees
//
//  Created by Xiaohan on 2018/12/25.
//  Copyright © 2018 xiaohan. All rights reserved.
//

#import "TransferViewController.h"
#import "UITextView+WZB.h"
#import "TransferConfirmationView.h"
#import "HMScannerViewController.h"
#import "EOSService.h"
#import "LMJDropdownMenu.h"
@interface TransferViewController ()<UITextFieldDelegate,LMJDropdownMenuDelegate,UITextViewDelegate>
@property (nonatomic,strong) UITextField *receiveTF;
@property (nonatomic,strong) UITextField *moneyTF;
@property (nonatomic,strong) UITextView *memoTV;
@property (nonatomic,strong) UILabel *remainingTipLab;
@property (nonatomic,strong) EOSService *eosService;
@property (nonatomic,weak) XThemeFlatButton *sureBtn;
@property (nonatomic,strong) LMJDropdownMenu *dropdownMenu;
@property (nonatomic,strong) NSString *code;
@property (nonatomic,strong) NSString *core_liquid_balance;
@property (nonatomic,strong) NSString *symbol;
@property (nonatomic,strong) NSMutableArray *myListToken;
@property (nonatomic,strong) Wallet *wallet;

@end

@implementation TransferViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.code = self.defaultTokenInfo.code;
    self.symbol = self.defaultTokenInfo.symbol;
    self.wallet = CURRENT_WALLET;
    [self setupUI];
    [self getCurrencyBalance];
    [self getTokenList];

    self.receiveTF.text = self.account;
    if (self.account.length) {
        self.sureBtn.enabled = ![self.receiveTF.text isEqualToString:CURRENT_WALLET.wallet_name];
        [self.sureBtn setTitle:XLocalized(@"不能给自己转账") forState:UIControlStateDisabled];
    }
}

#pragma mark - net
- (void)getCurrencyBalance{
    [self.eosService getAccountCurrencyBalanceCode:self.code account:CURRENT_WALLET.wallet_name symbol:self.symbol complete:^(BOOL success, NSString * _Nonnull errorMsg, TokenInfo * _Nonnull tokenInfo) {
        if (tokenInfo) {
            self.remainingTipLab.text = [NSString stringWithFormat:@"%@%@",XLocalized(@"余额"),tokenInfo.balance];
            self.core_liquid_balance = tokenInfo.balance;
            [self textDidChange:self.moneyTF];
        }
    }];
}
- (void)getTokenList{
    [self.eosService getMyTokenListComplete:^(BOOL success, NSString * _Nonnull errorMsg) {
        if (success) {
            NSMutableArray*tokenNames = @[].mutableCopy;
            for (TokenInfo*token in  self.eosService.wallet.myTokenList) {
                [tokenNames addObject:token.symbol];
                [self.myListToken addObject:token];
            }
            for (TokenInfo*token in  self.eosService.wallet.contracts) {
                [tokenNames addObject:token.symbol];
                [self.myListToken addObject:token];
            }
            [self.dropdownMenu setMenuTitles:tokenNames rowHeight:40];
        }else{
            //[self.view makeToast:errorMsg];
        }
    }];
}
#pragma mark - action
- (void)rightBtnClick{
    HMScannerViewController *scanner = [[HMScannerViewController alloc] initWithCardName:nil avatar:nil completion:^(NSString *stringValue) {
        if (![RegularExp validateEosAccountName:stringValue]) {
            [self.view makeToast:XLocalized(@"请输入正确的账户名")];
            return;
        }
        self.receiveTF.text = stringValue;
    }];
    [self.navigationController pushViewController:scanner animated:YES];
}



- (void)setupUI{
//     [self addNavigationItemWithImageNames:@[@"black_qcode"] isLeft:NO target:self action:@selector(rightBtnClick) tags:nil];
    self.title = XLocalized(@"转账");
    UILabel *tipLab = [UILabel new];
    tipLab.font = kBoldFont(16);
    tipLab.textColor = kTitleColor;
    tipLab.text = XLocalized(@"收款账号");
    [self.contentView addSubview:tipLab];
    [tipLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(AdaptedWidth(kNormalSpace));
        make.height.mas_equalTo(AdaptedWidth(16));
        make.top.mas_equalTo(AdaptedHeight(22));
    }];
    self.receiveTF = [UITextField new];
    [self.receiveTF setValue:@12 forKey:Limit_NAME];
    self.receiveTF.borderStyle = UITextBorderStyleNone;
    [self.contentView addSubview:self.receiveTF];
    [self.receiveTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(tipLab.mas_left);
        make.right.mas_equalTo(-kNormalSpace);
        make.height.mas_equalTo(AdaptedWidth(35));
        make.top.equalTo(tipLab.mas_bottom).offset(AdaptedHeight(12));
    }];
    self.receiveTF.font = kDefaultFont(13);
    self.receiveTF.layer.cornerRadius = AdaptedWidth(10);
    self.receiveTF.backgroundColor = UIColorHex(#F7F7F7);
//    contact_yellow
    UIButton* contactBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, AdaptedWidth(30), AdaptedWidth(30))];
    [contactBtn setImage:IMAGE_NAMED(@"black_qcode") forState:UIControlStateNormal];
    self.receiveTF.rightView = contactBtn;
    self.receiveTF.rightViewMode = UITextFieldViewModeAlways;
    kWeakSelf(self);
    [contactBtn addTapBlock:^(UIButton * _Nonnull btn) {
        [weakself rightBtnClick];
    }];
    
    UIView*letfV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 8, AdaptedWidth(30))];
    self.receiveTF.leftView = letfV;
    self.receiveTF.leftViewMode = UITextFieldViewModeAlways;
    self.receiveTF.placeholder = XLocalized(@"接收方");
    self.receiveTF.text = self.account;
    [self.receiveTF setValue:@12 forKey:Limit_NAME];
    
    UILabel *tipLab2 = [UILabel new];
    tipLab2.font = kBoldFont(16);
    tipLab2.textColor = kTitleColor;
    tipLab2.text = XLocalized(@"转账金额");
    [self.contentView addSubview:tipLab2];
    [tipLab2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(AdaptedWidth(kNormalSpace));
        make.height.mas_equalTo(AdaptedWidth(16));
        make.top.equalTo(self.receiveTF.mas_bottom).offset(AdaptedHeight(20));
    }];
    
    self.dropdownMenu = [[LMJDropdownMenu alloc]initWithFrame:CGRectZero];
    self.dropdownMenu.delegate = self;
    [self.dropdownMenu.mainBtn setTitle:self.symbol forState:UIControlStateNormal];;
    ViewBorderRadius(self.dropdownMenu, AdaptedWidth(10), CGFloatFromPixel(2), kColorMain);
    NSMutableArray*tokenNames = @[].mutableCopy;
    for (TokenInfo*token in  self.wallet.myTokenList) {
        [tokenNames addObject:token.symbol];
        [self.myListToken addObject:token];
    }
    for (TokenInfo*token in  self.wallet.contracts) {
        [tokenNames addObject:token.symbol];
        [self.myListToken addObject:token];
    }
    
    [self.dropdownMenu setMenuTitles:tokenNames rowHeight:40];
    
    [self.contentView addSubview:self.dropdownMenu];
    [self.dropdownMenu mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(AdaptedWidth(kNormalSpace));
        make.top.equalTo(tipLab2.mas_bottom).offset(AdaptedHeight(12));
        make.width.mas_equalTo(AdaptedWidth(70));;
        make.height.mas_equalTo(AdaptedWidth(35));
    }];
    
    
    self.moneyTF = [UITextField new];
    self.moneyTF.borderStyle = UITextBorderStyleNone;
    [self.contentView addSubview:self.moneyTF];
    [self.moneyTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.dropdownMenu.mas_right).offset(AdaptedWidth(10));
        make.centerY.equalTo(self.dropdownMenu.mas_centerY);
        make.right.mas_equalTo(-kNormalSpace);
        make.height.mas_equalTo(AdaptedWidth(35));
    }];
    self.moneyTF.font = kDefaultFont(13);
    self.moneyTF.layer.cornerRadius = AdaptedWidth(10);
    self.moneyTF.backgroundColor = UIColorHex(#F7F7F7);
    self.moneyTF.placeholder = XLocalized(@"转账金额");
    UIView*letfV1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 8, AdaptedWidth(30))];
    self.moneyTF.leftView = letfV1;
    self.moneyTF.leftViewMode = UITextFieldViewModeAlways;
    self.moneyTF.delegate = self;
    self.moneyTF.keyboardType = UIKeyboardTypeDecimalPad;
    self.remainingTipLab = [UILabel new];
    self.remainingTipLab.textColor = UIColorHex(#B5B5B5);
    self.remainingTipLab.font = kDefaultFont(10);
    [self.contentView addSubview:self.remainingTipLab];
    [self.remainingTipLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.moneyTF.mas_right);
        make.top.equalTo(self.moneyTF.mas_bottom).offset(AdaptedHeight(6));
    }];
    
    
    UILabel *tipLab3 = [UILabel new];
    tipLab3.font = kBoldFont(16);
    tipLab3.textColor = kTitleColor;
    tipLab3.text = XLocalized(@"备注");
    [self.contentView addSubview:tipLab3];
    [tipLab3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(AdaptedWidth(kNormalSpace));
        make.height.mas_equalTo(AdaptedWidth(16));
        make.top.equalTo(self.dropdownMenu.mas_bottom).offset(AdaptedHeight(35));
    }];
    
    self.memoTV = [UITextView new];
    self.memoTV.wzb_placeholder = XLocalized(@"备注");
    self.memoTV.layer.cornerRadius = AdaptedWidth(10);
    self.memoTV.backgroundColor = UIColorHex(#F7F7F7);
    self.memoTV.font = kDefaultFont(13);
    self.memoTV.delegate = self;
    self.memoTV.returnKeyType = UIReturnKeyDone;;
//    [self.memoTV setValue:@50 forKey:Limit_NAME];
    [self.contentView addSubview:self.memoTV];
    [self.memoTV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(tipLab.mas_left);
        make.right.mas_equalTo(-kNormalSpace);
        make.height.mas_equalTo(AdaptedWidth(35));
        make.top.equalTo(tipLab3.mas_bottom).offset(AdaptedHeight(12));
    }];
    self.memoTV.wzb_minHeight = AdaptedWidth(35);
    [self.memoTV wzb_autoHeightWithMaxHeight:AdaptedWidth(100)];

    
    XThemeFlatButton *sureBtn = [XThemeFlatButton button];
    self.sureBtn = sureBtn;
    [sureBtn setTitle:XLocalized(@"确认") forState:UIControlStateNormal];
    [self.contentView addSubview:sureBtn];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.bottom.mas_equalTo(-AdaptedWidth(43));;
        make.height.mas_equalTo(AdaptedWidth(40));
        make.top.equalTo(self.memoTV.mas_bottom).offset(AdaptedHeight(239));
    }];
    
    [self.receiveTF addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.moneyTF addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];

    [sureBtn addTapBlock:^(UIButton * _Nonnull btn) {
        TransferModel*info = [TransferModel new];
        if (!weakself.receiveTF.text.length) {
            [weakself.view makeToast:XLocalized(@"请输入收款账户名")];
            return;
        }
        if (![RegularExp validateEosAccountName:weakself.receiveTF.text]) {
            [weakself.view makeToast:XLocalized(@"请输入正确的账户名")];
            return;
        }
        if (!weakself.moneyTF.text.length || weakself.moneyTF.text.floatValue == 0) {
            [weakself.view makeToast:weakself.moneyTF.placeholder];
            return;
        }
        info.from = CURRENT_WALLET.wallet_name;
        info.to = weakself.receiveTF.text;
        info.quantity = [NSString stringWithFormat:@"%.4f %@",weakself.moneyTF.text.floatValue,self.symbol];
        info.memo = weakself.memoTV.text?:@"";
        [TransferConfirmationView showInfo:info sureAction:^(TransferModel*transferModel){
            [WalletTool checkPrivateInputPasswordWith:CURRENT_WALLET complete:^(BOOL result,NSString * _Nonnull privateKey) {
                if (result) {
                    weakself.eosService.privateKey = privateKey;
                    weakself.eosService.action = ContractAction_TRANSFER;
                    weakself.eosService.actor = CURRENT_WALLET.wallet_name;
                    weakself.eosService.account = self.code;
                    weakself.eosService.available_keys = @[VALIDATE_STRING(CURRENT_WALLET.wallet_public_key)];
                    [MBProgressHUD showLoadTitile:@"" ToView:weakself.view];
                    [weakself.eosService transferFrom:transferModel.from To:transferModel.to quantity:transferModel.quantity memo:transferModel.memo complete:^(BOOL success, NSString * _Nonnull msg) {
                        [MBProgressHUD hideHUDForView:weakself.view];
                        if (success) {
                            Receive *receive = [Receive new];
                            receive.wallet_name = transferModel.to;
                            receive.addTime = [TimeHelper getCurrentTimeFormat:@"yyyy-MM-dd HH:mm"];
                            [[XHDataBaseManager shareInstance]saveHistoryWallet:CURRENT_WALLET.wallet_name receiveName:receive];
                            [kAppWindow makeToast:msg];
                            [weakself backBtnClicked];
                        }else{
                            [weakself.view makeToast:msg];
                        }
                    }];
                }
            }];
            
        }];
    }];
}

- (void)textDidChange:(UITextField*)textField{
    if (textField == self.receiveTF) {
      self.sureBtn.enabled = ![self.receiveTF.text isEqualToString:CURRENT_WALLET.wallet_name];
      [self.sureBtn setTitle:XLocalized(@"不能给自己转账") forState:UIControlStateDisabled];
    }else{
       self.sureBtn.enabled =  SNCompare([self.core_liquid_balance getDigital], self.moneyTF.text) != NSOrderedAscending;
       [self.sureBtn setTitle:XLocalized(@"余额不足") forState:UIControlStateDisabled];
    }
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    return [RegularExp controllTheAmountfNumberWithString:textField shouldChangeCharactersInRange:range replacementString:string maxDecimalLength:kSymbolLength_EOS];
}
#pragma mark- textView

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        return NO;
    }
    return YES;
}


#pragma mark- 
- (void)dropdownMenu:(LMJDropdownMenu *)menu selectedCellNumber:(NSInteger)number{
    TokenInfo*token = [self.myListToken objectOrNilAtIndex:number];
    if (token) {
        self.code = token.code;
        self.symbol = token.symbol;
    }
    [self getCurrencyBalance];
}
#pragma mark - getter
- (EOSService*)eosService{
    if (!_eosService) {
        _eosService = [EOSService new];
    }
    return _eosService;
}
- (NSMutableArray *)myListToken{
    if (!_myListToken) {
        _myListToken = [NSMutableArray array];
    }
    return _myListToken;
}

- (TokenInfo*)defaultTokenInfo{
    if (!_defaultTokenInfo) {
        _defaultTokenInfo = [TokenInfo new];
        _defaultTokenInfo.code =  kContractName_EOSIOTOKEN;
        _defaultTokenInfo.symbol = kSymbolName_EOS;
    }
    return _defaultTokenInfo;
}
@end
